<?php
// +----------------------------------------------------------------------
// | ebSIG
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.ebsig.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: liudaojian <liudaojian@ebsig.com>
// +----------------------------------------------------------------------

/**
 * redis锁定服务
 * 并发访问限制
 * @author   liudaojian <liudaojian@ebsig.com>
 * @version 1.0
 */

namespace App\Service;

use Illuminate\Support\Facades\Redis as Redis;

class LockingService
{

    private static $redis_index;

    /**
     * 检查是否有锁定服务
     * @param string $redis_index redis名称
     * @param int $expire 锁定时间
     * @return bool
     */
    public static function check($redis_index, $expire = 3600)
    {

        $lock = false; //是否要锁定  true：要锁定 false：不要锁定

        self::$redis_index = $redis_index;

        $res = Redis::setnx($redis_index, time() + $expire); //新增或更新数据，如果key已存在值，则不能更新
        if (!$res) {
            //更新失败，表示锁已存在，
            $time = Redis::get($redis_index); //获取锁的过期时间
            if ( $time >= time()) { //未过期
                $lock = true;
            } else { //已过期
                self::remove(); //删除锁
                Redis::setnx($redis_index, time() + $expire); //重新添加锁
            }
        }

        return $lock;

    }

    /**
     * 删除锁定服务
     * @return mixed
     */
    public static function remove()
    {
        return Redis::del(self::$redis_index);
    }
    
}